package com.example.demo07cache.listener;

import com.example.demo07cache.event.RedisDeleteKeyEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisKeyExpiredEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author wangxun
 */
@Slf4j
@Component
public class MyListeners {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * Redis Key 过期监听器 (如果 Redis 中有 Key 过期的话会监听到)
     */
    @Async
    @EventListener
    public void redisKeyExpirationListener(RedisKeyExpiredEvent event) {
        // user:1001  --> 1001
        // english:activity:student:1001  -->  activity:student:1001
        System.out.println(StringUtils.toEncodedString(event.getId(), StandardCharsets.UTF_8));
        // user:1001  --> user
        // english:activity:student:1001  -->  english
        System.out.println(event.getKeyspace());
        // user:1001  --> user:1001
        // english:activity:student:1001  -->  english:activity:student:1001
        System.out.println(StringUtils.toEncodedString(event.getSource(), StandardCharsets.UTF_8));
        // 时间戳  -->  1625243519693
        System.out.println(event.getTimestamp());
    }

    /**
     * Redis Key 删除监听器 (如果 Redis 中有 Key 删除的话会监听到)
     */
    @Async
    @EventListener
    public void redisDeleteKeyEventListener(RedisDeleteKeyEvent event) {
        String redisKey = event.getRedisKey();
        redisTemplate.delete(redisKey);
        log.info("删除RedisKey: {}", redisKey);
    }
}
